﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Model;

namespace WebApi.Controllers
{
    /// <summary>
    /// 发货单位
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class SenderListController : BaseController
    {
        public SenderListController(ILogger<SenderListController> logger) : base(logger)
        {
        }

        [HttpPost("Add")]
        public async Task<ReturnModel> Add(SenderList model)
        {
            return await Save(model, true);
        }

        [HttpPost("Update")]
        public async Task<ReturnModel> Update(SenderList model)
        {
            return await Save(model, false);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isInsert"></param>
        /// <returns></returns>
        private async Task<ReturnModel> Save(SenderList model, bool isInsert)
        {
            try
            {
                logger.LogDebug($"isInsert={isInsert};" + JsonConvert.SerializeObject(model));
                if (DbHelper.SenderList.IsAny(c => c.sender == model.sender && c.id != model.id))
                    return logger.Code_202("发货单位已存在");
                else if (isInsert)
                    await DbHelper.SenderList.InsertAsync(model);
                else
                    await DbHelper.GetDbConn().Updateable(model).ExecuteCommandAsync();
                LogToDB("SenderList", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("SenderList", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(Save)}-{ex.Message}");
                return logger.ErrorModel(nameof(SenderListController) + "-" + nameof(Save), ex);
            }
        }

        /// <summary>
        /// 获取发货单位列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetList")]
        public async Task<ReturnModel> GetList()
        {
            try
            {
                List<SenderList> data = await DbHelper.SenderList.GetListAsync();
                return new ReturnModel { Count = data.Count, Data = data };
            }
            catch (Exception ex)
            {
                return logger.ErrorModel($"{nameof(SenderListController)}/{nameof(GetList)}", ex);
            }
        }

        /// <summary>
        /// 获取发货单位下拉框数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("SelectList")]
        public async Task<ReturnModel> SelectList()
        {
            try
            {
                var list = await DbHelper.SenderList.AsQueryable().Select(it => it.sender).ToListAsync();
                return new ReturnModel { Count = list.Count, Data = list };
            }
            catch (Exception ex)
            {
                return logger.ErrorModel($"{nameof(SenderListController)}/{nameof(SelectList)}", ex);
            }
        }

        ///// <summary>
        ///// 获取客户类型下拉框数据
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("SelectCustomerTypeList")]
        //public async Task<ReturnModel> SelectCustomerTypeList()
        //{
        //    try
        //    {
        //        var list = await DbHelper.SenderList.AsQueryable().Where(it=>SqlFunc.HasValue(it.remarktext)).Select(it => it.remarktext).Distinct().ToListAsync();
        //        return new ReturnModel { Count = list.Count, Data = list };
        //    }
        //    catch (Exception ex)
        //    {
        //        return logger.ErrorModel($"{nameof(SenderListController)}/{nameof(SelectCustomerTypeList)}", ex);
        //    }
        //}
    }
}